package cn.t.utils;

import cn.t.constants.ParamConstants;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.enums.WriteDirectionEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author l
 */
public class ExcelUtil {
    public static void setHeader(HttpServletResponse response,String name){
            response.setContentType(ParamConstants.DOWNLOAD_CONTENT_TYPE_1);
            response.setContentType(ParamConstants.DOWNLOAD_CONTENT_TYPE_2);
            String fileName = name + ParamConstants.XLSX;
            response.addHeader(ParamConstants.HEADER_DISPOSITION, ParamConstants.HEADER_CONTENT_DISPOSITION
                    + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));

            // 自定义 header 并暴露给调用者
            response.setHeader(ParamConstants.ACCESS_CONTROL_EXPOSE_HEADERS, ParamConstants.CUSTOMIZE_HEADER);
            response.setHeader(ParamConstants.CUSTOMIZE_HEADER, fileName);
    }
    public static void exportExcel(HttpServletResponse response, List<?> list, Object obj,
                                   String templateFileName,String fileName) throws Exception {
        setHeader(response,new SimpleDateFormat("").format(new Date()).concat(fileName));
        ClassPathResource cpr = new ClassPathResource(templateFileName);
        InputStream is = cpr.getInputStream();
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(is).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().direction(WriteDirectionEnum.VERTICAL).forceNewRow(Boolean.FALSE).build();
        excelWriter.fill(new FillWrapper(list), fillConfig, writeSheet);
          excelWriter.fill(obj, writeSheet);
        //关闭
        excelWriter.finish();
    }
    public static OutputStream getOutputStream(String Name, HttpServletResponse response) throws Exception {
        //这里是对文件的重命名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
        String date = sdf.format(new Date());
        String fileName = new String(Name.getBytes(), StandardCharsets.UTF_8) + date + ".xlsx";
        // 这里文件名如果涉及中文一定要使用URL编码,否则会乱码
        response.setContentType("application/force-download");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        return response.getOutputStream();
    }
}
